<template>
  <div class="xmind-list-work">
    <div class="top-operate-group">
      <div class="operate-modal" @click="handleCreateMind">
        <div class="logo">
          <img src="@/assets/images/home/add-mind.png" alt="">
        </div>
        <div class="desc">
          <p class="name">新建导图</p>
          <p class="tip">在新导图上展开你的想法</p>
        </div>
      </div>
      <div class="operate-modal" @click="newFolderVisible = true">
        <div class="logo">
          <img src="@/assets/images/home/add-folder.png" alt="">
        </div>
        <div class="desc">
          <p class="name">新建文件夹</p>
          <p class="tip">快捷管理你的思维导图</p>
        </div>
      </div>
      <div class="operate-modal">
        <div class="logo">
          <img src="@/assets/images/home/upload-file.png" alt="">
        </div>
        <div class="desc">
          <p class="name">上传文件</p>
          <p class="tip">从你的设备上传文件</p>
        </div>
      </div>
    </div>

    <CardGrid
      v-show="grid === 'card'"
      :folderList="folderList"
      :mindList="mindList"
      :skeletonLoading="skeletonLoading"
      showFolder
      @refresh-page="queryFolderAndMindList"
      @update-collect-status="updateCollectStatus"
      @folder-click="handleFolderClick"
      @mind-click="handleMindClick" />

    <ListGrid
      v-show="grid === 'list'"
      :folderList="folderList"
      :mindList="mindList"
      :skeletonLoading="skeletonLoading"
      showFolder
      @refresh-page="queryFolderAndMindList"
      @update-collect-status="updateCollectStatus"
      @folder-click="handleFolderClick"
      @mind-click="handleMindClick" />

    <NewFolderMind
      v-if="newFolderVisible"
      operateType="folder"
      :folderId="folderId"
      @close-modal="handleCloseModal" />
  </div>
</template>

<script setup lang="ts">
import { ref, defineProps, PropType, onBeforeUnmount } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { storeToRefs } from 'pinia'
import mitter from '@/mitt'
import { commonStore } from '@/store/common.store'
import { initXmindMapJson } from '@/pages/mind-map/config'
import { apiGetFolderList, apiGetMindList, apiGetFolderUpPaths, apiCreateMind } from '@/apis/work'
import CardGrid from '@/pages/home/components/CardGrid.vue'
import ListGrid from '@/pages/home/components/ListGrid.vue'
import NewFolderMind from './components/NewFolderMind.vue'
import type { Folder, Mind } from '@/types'

defineProps({
  grid: {
    type: String as PropType<'card' | 'list'>,
    default: 'card'
  }
})
const [route, router] = [useRoute(), useRouter()]
const { workBreadCrumbs } = storeToRefs(commonStore())

const folderList = ref<Folder[]>([])
const mindList = ref<Mind[]>([])

const folderId = route.params.id as string
const searchKeywords = ref('')

const skeletonLoading = ref(false)
/**
 * 文件夹列表和导图列表查询
 */
const queryFolderAndMindList = async () => {
  skeletonLoading.value = true
  try {
    const data = await Promise.all(
      [
        apiGetFolderList<Folder[]>({ name: searchKeywords.value, folderId }),
        apiGetMindList<Mind[]>({ name: searchKeywords.value, folderId })
      ]
    )
    folderList.value = data[0]
    mindList.value = data[1]
    skeletonLoading.value = false
  } catch (error) {
    router.push('/home/work')
    skeletonLoading.value = false
  }
}
queryFolderAndMindList()

/**
 * 当前文件夹所处路径地址查询
 */
const queryFolderUpPaths = async () => {
  if (folderId) {
    const data = await apiGetFolderUpPaths<Folder[]>(folderId)
    workBreadCrumbs.value = [{ title: '我的导图', routePath: '/home/work' }].concat(...data.map(m => {
      return {
        title: m.name,
        routePath: `/home/work/${m.id}`
      }
    }))
  } else {
    workBreadCrumbs.value = [{ title: '我的导图', routePath: '/home/work' }]
  }
}
queryFolderUpPaths()

const createMindLoading = ref(false)
/**
 * 导图创建
 */
const handleCreateMind = async () => {
  if (createMindLoading.value) return
  createMindLoading.value = true
  try {
    const mindJson = [initXmindMapJson()]
    const mindId = await apiCreateMind({ name: '我的导图', folderId, mindJson })
    router.push(`/mind-map/${mindId}`)
  } finally {
    createMindLoading.value = false
  }
}

/**
 * 静态更新导图的收藏状态
 * @param mindId
 * @param status
 */
const updateCollectStatus = (mindId: string, status: boolean) => {
  const mind = mindList.value.find(m => m.id === mindId)
  if (mind) {
    mind.isCollected = status ? 1 : 0
  }
}

const newFolderVisible = ref(false)

const handleCloseModal = (refresh) => {
  if (refresh) {
    queryFolderAndMindList()
  }
  newFolderVisible.value = false
}

const handleFolderClick = (folderItem: Folder) => {
  router.push(`/home/work/${folderItem.id}`)
}

const handleMindClick = (mindItem: Mind) => {
  router.push(`/mind-map/${mindItem.id}`)
}

mitter.on('search-mind-list', function (keywords?: any) {
  searchKeywords.value = keywords
  queryFolderAndMindList()
})

mitter.on('bread-crumb-click', function (breadCrumb: any) {
  router.push(breadCrumb.routePath)
})

onBeforeUnmount(() => {
  mitter.off('bread-crumb-click')
  mitter.off('search-mind-list')
})
</script>

<style lang="scss" scoped>
.xmind-list-work {
  .top-operate-group {
    display: flex;
    gap: 24px;
    .operate-modal {
      display: flex;
      flex-grow: 1;
      max-width: 416px;
      border-radius: 8px;
      border: 1px solid rgba(0, 0, 0, .08);
      padding: 24px;
      align-items: center;
      cursor: pointer;
      &:hover {
        background-color: rgba(0, 0, 0, .03);
      }
      .logo img {
        display: block;
        width: 48px;
        margin-right: 18px;
      }
      .desc {
        .name {
          font-weight: 600;
          font-size: 18px;
        }
        .tip {
          color: #999;
          font-size: 14px;
          margin-top: 4px;
        }
      }
    }
  }
}
</style>
